requireJS(['constant', 'site', 'handlebars'], function (Constant, site, Handlebars) {

    var url = {
        selectEducation: "manager/selectEducation.do",
        selectMarry: "manager/selectMarry.do",
        selectInfoByCard: "manager/selectInfoByCard.do",
        ajaxqueryRegion: "manager/ajaxqueryRegion.do",
    };

    var locked;
    var personalId;
    var productId = getAurlparam('productId');
    if (getAurlparam('pid')) {
        url.addOrEdit = 'manager/updatePersonalPublic.do'
    } else {
        url.addOrEdit = 'manager/InsertPersonalPublic.do'
    }

    var pid = getAurlparam('pid');
    var borrowersIndex;
    Handlebars.registerHelper('if_eq', function (v1, v2, opts) {
        if (v1 == v2)
            return opts.fn(this);
        else
            return opts.inverse(this);
    });
    Handlebars.registerHelper("addOne", function (index) {
        //返回+1之后的结果
        return index + 1;
    });

    //省市区联动
    site.send({
        url: url.ajaxqueryRegion,
        data: {
            parentId: 0
        },
        callback: function (data) {
            data = JSON.parse(data);
            var source = $("#province_list_tpl").html();
            var template = Handlebars.compile(source);
            var list = data
            var html = template(list)
            $('#province_list').append(html)
            $('#rprovince_list').append(html)
        }
    })

    $("#province_list").on("change", function () {
        if (!$(this).val()) {
            $("#city_list").html('<option value="" selected="selected">选择市</option>');
            $("#area_list").html('<option value="" selected="selected">选择区县</option>');
        }
        else {
            site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: $(this).val()
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#city_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#city_list').html(html)
                }
            })
        }
    })

    $("#city_list").on("change", function () {
        if (!$(this).val()) {
            $("#area_list").html('<option value="" selected="selected">选择区县</option>');
        } else {
            site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: $(this).val()
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#area_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#area_list').html(html)
                }
            })
        }
    })

    $("#rprovince_list").on("change", function () {
        if (!$(this).val()) {
            $("#rcity_list").html('<option value="" selected="selected">选择市</option>');
            $("#rarea_list").html('<option value="" selected="selected">选择区县</option>');
        }
        else {
            site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: $(this).val()
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#rcity_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#rcity_list').html(html)
                }
            })
        }
    })

    $("#rcity_list").on("change", function () {
        if (!$(this).val()) {
            $("#rarea_list").html('<option value="" selected="selected">选择区县</option>');
        } else {
            site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: $(this).val()
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#rarea_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#rarea_list').html(html)
                }
            })
        }
    })

    function fillFormData() {
        site.send({
            url: 'manager/selectPersonalPublicInfo.do',
            //async:false
            data: {pid: pid, product_id: productId},
            callback: function (data) {
                var list = JSON.parse(data)
                if (list.type == '1') {
                    locked = list.content.personalDatas.locked;
                    borrowersIndex = list.content.personalDatas.borrowerDatas.length
                    var template = Handlebars.compile($("#borrowers_content_tpl").html())
                    var html = template(list)
                    $("#borrowers_content").prepend(html)
                    addBlur();

                    personalId = list.content.personalDatas.id ? list.content.personalDatas.id : "";
                    $("#create_time").text(list.content.personalDatas.create_time);
                    //日期控件初始化
                    $(".datepicker").datepicker({
                        format: 'yyyy-mm-dd',
                        autoclose: true,
                        pickerPosition: 'bottom',
                    })
                    del();

                    for (var k in list.content.personalDatas.borrowerDatas) {
                        if (list.content.personalDatas.borrowerDatas[k].sex == '1') {
                            $('._borrowers').eq(k).children('td').children('.pad').children('.sex-radio').eq(0).addClass('is-checked');
                            $('._borrowers').eq(k).children('td').children('.pad').children('.sex-radio').eq(1).removeClass('is-checked')
                            $('._borrowers').eq(k).children('td').children('.pad').children('.sex-radio').eq(0).children('input').attr('checked', true)
                            $('._borrowers').eq(k).children('td').children('.pad').children('.sex-radio').eq(1).children('input').attr('checked', false)
                        }
                        if (list.content.personalDatas.borrowerDatas[k].sex == '2') {
                            $('._borrowers').eq(k).children('td').children('.pad').children('.sex-radio').eq(1).addClass('is-checked');
                            $('._borrowers').eq(k).children('td').children('.pad').children('.sex-radio').eq(0).removeClass('is-checked')
                            $('._borrowers').eq(k).children('td').children('.pad').children('.sex-radio').eq(1).children('input').attr('checked', true)
                            $('._borrowers').eq(k).children('td').children('.pad').children('.sex-radio').eq(0).children('input').attr('checked', false)
                        }
                    }

                    sexFun();
                    $("#create_time").html(list.content.personalDatas.create_time)
                    $("#edit_time").html(Constant.getNowFormatDate());

                    $("#personal_num").text(list.content.personalDatas.personal_num)
                    $("#payee").val(list.content.personalDatas.payee)
                    $("#account").val(list.content.personalDatas.account)
                    $("#bank").val(list.content.personalDatas.bank)


                    //$(".huArea .huInput").val(list.content.personalDatas.addr_p_name + list.content.personalDatas.addr_a_name + list.content.personalDatas.addr_c_name);
                    //$(".homeArea .homeInput").val(list.content.personalDatas.resid_p_name + list.content.personalDatas.resid_a_name + list.content.personalDatas.resid_c_name);
                    $("#residence").val(list.content.personalDatas.residence)
                    $("#address").val(list.content.personalDatas.address)

                    $("#province_list").val(list.content.personalDatas.resid_province)

                    var list2 = list;

                    site.send({
                        url:url.ajaxqueryRegion,
                        data: {
                            parentId: list2.content.personalDatas.resid_province
                        },
                        callback: function (data) {
                            data = JSON.parse(data);
                            var source = $("#city_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data
                            var html = template(list)
                            $('#city_list').html(html)
                            $("#city_list").val(list2.content.personalDatas.resid_city)
                        }
                    })

                    site.send({
                        url: url.ajaxqueryRegion,
                        data: {
                            parentId: list2.content.personalDatas.resid_city
                        },
                        callback: function (data) {
                            data = JSON.parse(data);
                            var source = $("#area_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data
                            var html = template(list)
                            $('#area_list').html(html)
                            $("#area_list").val(list2.content.personalDatas.resid_area);
                        }
                    })



                    $("#rprovince_list").val(list.content.personalDatas.addr_province);
                    site.send({
                        url:url.ajaxqueryRegion,
                        data: {
                            parentId: list2.content.personalDatas.addr_province
                        },
                        callback: function (data) {
                            data = JSON.parse(data);
                            var source = $("#rcity_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data
                            var html = template(list)
                            $('#rcity_list').html(html)
                            $("#rcity_list").val(list2.content.personalDatas.addr_city);
                        }
                    })

                    site.send({
                        url:url.ajaxqueryRegion,
                        data: {
                            parentId: list2.content.personalDatas.addr_city
                        },
                        callback: function (data) {
                            data = JSON.parse(data);
                            var source = $("#rarea_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data
                            var html = template(list)
                            $('#rarea_list').html(html)
                            $("#rarea_list").val(list2.content.personalDatas.addr_area);
                        }
                    })

                    $(".PersonCol3 input").each(function () {
                        if ($(this).val() == list.content.personalDatas.house) {
                            $(this).attr('checked', true)
                            $(this).siblings('input').attr('checked', false)
                        }
                    })
                    $("#homephone").val(list.content.personalDatas.homephone)
                    if (list.content.personalDatas.education) {
                        $("#education_list > option[value=" + list.content.personalDatas.education + "]").prop('selected', true);
                    }
                    if (list.content.personalDatas.marry) {
                        $("#marry_list > option[value=" + list.content.personalDatas.marry + "]").prop('selected', true);
                    }
                    $("#child").val(list.content.personalDatas.child)
                    $("#begin_time").val(list.content.personalDatas.begin_time)
                    $("#local_time").val(list.content.personalDatas.local_time)

                    var personalRealDatas = list.content.personalRealDatas;
                    if (personalRealDatas) {
                        $.each(personalRealDatas, function (index, item) {
                            var type = item.type
                            /*if(index <= 5){
                                $('td[define_id='+item.property_id+']').attr('op_id',item.id);
                                switch(type){
                                    case 'select':
                                        $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                        break;
                                    case 'text':
                                        $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                        break;
                                    case 'radio':
                                        $('td[define_id='+item.property_id+'] input[content_id='+item.content_ids+']').attr('checked',true);
                                        break;
                                }
                                /!*if(type == 'select'){
                                    $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                }
                                if(type == 'text'){
                                    $('td[define_id='+item.property_id+'] input[type="text"]').val(item.value);
                                }
                                if(type == 'radio'){
                                    $('td[define_id='+item.property_id+'] input[content_id='+item.content_ids+']').attr('checked',true);
                                }*!/
                            }*/
                            $('#apply-PersonMess .component[id=' + item.property_id + ']').attr('op_id', item.id);
                            switch (type) {
                                case 'form_name':
                                    $('#apply-PersonMess .component legend').val(item.value);
                                    break;
                                case 'checkbox': {
                                    if (item.content_ids) {
                                        var content_ids = item.content_ids;
                                        content_ids = content_ids.split(',');
                                        $.each(content_ids, function (i, e) {
                                            $('#apply-PersonMess .component[id=' + item.property_id + '] input[content_id=' + e + ']').attr('checked', true);
                                        })
                                    }
                                    break;
                                }

                                case 'select':
                                    if (item.content_ids) {
                                        $('#apply-PersonMess .component[id=' + item.property_id + '] option[content_id=' + item.content_ids + ']').attr('selected', true);
                                    }
                                    break;
                                case 'radio':
                                    if (item.content_ids) {
                                        $('#apply-PersonMess .component[id=' + item.property_id + '] input[content_id=' + item.content_ids + ']').attr('checked', true);
                                    }
                                    break;
                                case 'text':
                                    $('#apply-PersonMess .component[id=' + item.property_id + '] input[type="text"]').val(item.value);
                                    break;
                                case 'textarea':
                                    $('#apply-PersonMess .component[id=' + item.property_id + '] textarea').val(item.value);
                                case 'time':
                                    $('#apply-PersonMess .component[id=' + item.property_id + '] input[type="text"]').val(item.value);
                            }
                        })
                    }

                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }
        })
    }


    $(".datepicker").datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        pickerPosition: 'bottom',
    })
    //表单验证
    //查询出要固定表单和自定义表单
    function queryForm() {
        site.send({
            url: "manager/selectProductFormCustom.do",
            data: {
                product_id: productId
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    //渲染客户自定义部分
                    if (data.content.personalPropertyCategorys) {
                        $.each(data.content.personalPropertyCategorys, function (index, item) {
                            $('#apply-PersonMess .form_myself').append('<div id="pcategorys' + index + '" style="overflow: hidden;"></div>');
                            $.each(item.personalPropertyDefines, function (index2, item2) {
                                $("#pcategorys" + index).append(item2.define_html);
                            })
                            /*if(index == 0){
                                $('#add_form').before(item.template_html);
                            }*/
                            //else{
                            //$('.form_myself').append("<div style='overflow: hidden;'>" + item.template_html + "</div>");
                            //}
                        })
                    }
                    //渲染时间控件
                    $("[leipiplugins='time']").datepicker({
                        format: 'yyyy-mm-dd',
                        autoclose: true,
                        pickerPosition: 'bottom',
                    })

                    if (getAurlparam('pid')) {
                        $("#editOrAdd").text("编辑借款人信息")
                        fillFormData();
                    } else {

                        borrowersIndex = 1;
                        var list = {
                            "content": {
                                "personalDatas": {
                                    "borrowerDatas": [{
                                        "sex": '',
                                        "birth_date": "",
                                        "id_card": "",
                                        "cellphone": "",
                                        "real_name": "",
                                    }],
                                },
                            }
                        };
                        var template = Handlebars.compile($("#borrowers_content_tpl").html())

                        var html = template(list)
                        $("#borrowers_content").prepend(html)
                        addBlur();

                        //日期控件初始化
                        $(".datepicker").datepicker({
                            format: 'yyyy-mm-dd',
                            autoclose: true,
                            pickerPosition: 'bottom',
                        })



                        del();
                        sexFun();
                        $("#editOrAdd").text("新增借款人信息")
                    }
                }

                /*$.each(data.content.productPropertyCategorys,function(index,Categorys){
                    //$(".public-content").attr('')
                    $.each(Categorys.productPropertyDefines,function(index,Defines){
                        $('[leipiplugins][name='+Defines.name+']').attr('define_id',Defines.define_id);
                        var that = $('[leipiplugins][name='+Defines.name+']');
                        $.each(Defines.productPropertyContents,function(index,Contents){
                            //$('[name='+Contents.name+']').attr('content_id',Contents.content_id);
                            that.children().eq(index).attr('content_id',Contents.content_id);
                        })
                    })
                })*/
                else {
                    Constant.fn.Message('F', data.msg)
                }
            }, callError: function () {

            }
        })
    }

    queryForm();

    $(".pad .sex-radio").click(function () {
        $(this).addClass('is-checked');
        $(this).siblings().removeClass('is-checked')
        $(this).children('input').attr('checked', true)
        $(this).siblings().children('input').attr('checked', false)

    })


    //实现智能联想
    var searData = {};  //用来存储地址信息

    var Intelligent_association = {

        creSele: function (obj) {
            var autocomplete = $(obj.el).autocomplete({
                hints: obj.data,
                width: obj.width,
                height: obj.height,
                val: obj.val,
                inputClass: obj.inputClass,
                placeholder: obj.placeholder,
                onSubmit: function (text) {
                    obj.backball(text)
                }
            })
            return autocomplete
        },

        initHuArea: function (idxData) {
            var _this = this;
            var huArea = _this.creSele({						//户口所在地
                el: '.huArea',							//页面上的span节点
                data: '',								//需要搜索的所有数据
                width: 158,
                height: 32,
                val: idxData,									//默认input值
                inputClass: 'huInput',					//把动态生成的input class写进去 以免影响插件原有class
                placeholder: '请输入检索城市名称',
                backball: function (text) {				//用户选择后返回的值
                    searData.huArea = text
                    //console.log(text)
                }
            })
            $('.huInput').bind('keyup keydown', function (e) {		//监听用户敲击键盘时搜索数据
                if (e.which > 32 && e.which < 126) return
                if (/^[\u4e00-\u9fa5]*$/.test($(this).val())) {
                    huArea.hints = _this.getCity()				//赋值数据进插件对象huArea
                }
            })
        },

        initHomeArea: function (idxData) {
            var _this = this
            var homeArea = _this.creSele({
                el: '.homeArea',							//页面上的span节点
                data: '',								//需要搜索的所有数据
                width: 158,
                height: 32,
                val: idxData,							//默认input值
                inputClass: 'homeInput',					//把动态生成的input class写进去 以免影响插件原有class
                placeholder: '请输入检索城市名称',
                backball: function (text) {				//用户选择后返回的值
                    searData.homeArea = text

                }
            })
            $('.homeInput').bind('keyup keydown', function (e) {		//监听用户敲击键盘时搜索数据
                if (e.which > 32 && e.which < 126) return
                if (/^[\u4e00-\u9fa5]*$/.test($(this).val())) {
                    homeArea.hints = _this.getCity()						//赋值数据进插件对象huArea
                }
            })
        },

        /*获取json文件中的城市*/
        getCity: function () {
            var city;
            $.ajax({
                type: 'get',
                url: 'static/cityjson.json',
                async: false,
                success: function (data) {
                    city = data
                }
            })
            return city
        },

        /*获取完json数据后转成id 传给后台*/
        getSearId: function (data) {
            var id, city = this.getCity()
            $.each(city, function (idx, item) {
                if (item.name == data) {
                    id = item.id.split(',')
                    return
                }
            })
            return id
        }
    }

    //初始化智能搜索
    Intelligent_association.initHuArea();
    Intelligent_association.initHomeArea();

    //获取教育程度接口
    site.send({
        url: url.selectEducation,
        callback: function (data) {
            data = JSON.parse(data);
            if (data.type == 1) {
                var source = $("#education_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = data.content
                var html = template(list)
                $('#education_list').append(html)
            }
        }
    })
    //婚姻状况
    site.send({
        url: url.selectMarry,
        callback: function (data) {
            data = JSON.parse(data);
            if (data.type == 1) {
                var source = $("#marry_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = data.content
                var html = template(list)
                $('#marry_list').append(html)
            }
        }
    })

    $("#addBorrowingName").unbind().click(function () {
        borrowersIndex++;
        $("._borrowers").eq(borrowersIndex - 2).after('<tr ng-repeat="(key,item) in data._borrowers track by $index" class="personMess ng-scope _borrowers">\n' +
            '\t\t\t\t<td class="ng-binding"><span>*</span>借款人' + borrowersIndex + '</td>\n' +
            '\t\t\t\t<td colspan="7" style="text-align: left">\n' +
            '\t\t\t\t\t\t<span class="pad">\n' +
            '\t\t\t\t\t\t\t<input ng-class="{\'error\':_err.borrTis[$index].realName}" ng-focus="remFocus()" type="text" placeholder="请输入借款人' + borrowersIndex + '" ng-model="item.realName" class="realName ng-pristine ng-untouched ng-valid ng-empty">\n' +
            '\t\t\t\t\t\t</span>\n' +
            '\t\t\t\t\t<span class="pad">\n' +
            '\t\t\t\t\t\t\t<input placeholder="输入身份证号码" ng-class="{\'error\':_err.borrTis[$index].idCard}" ng-focus="remFocus()" type="text" style="width:220px" ng-model="item.idCard" ng-blur="getIdCard(key)" class="id_card ng-pristine ng-untouched ng-valid ng-empty">\n' +
            '\t\t\t\t\t\t</span>\n' +
            '\t\t\t\t\t<label class="labelinput pad" ng-class="{\'error\':_err.borrTis[$index].birthDate}">\n' +
            '\t\t\t\t\t\t<input ng-focus="remFocus()" placeholder="请选择生日" type="text" ng-model="item.birthDate" class="birth_date bothDate2 ng-empty datepicker">\n' +
            '\t\t\t\t\t\t<span>\n' +
            '\t\t \t\t\t\t\t\t<i class="iconfont icon-riqi"></i>\n' +
            '\t\t \t\t\t\t\t</span>\n' +
            '\t\t\t\t\t</label>\n' +
            '\t\t\t\t\t<span class="pad">\n' +
            '\t\t\t\t\t\t\t<input onkeyup="value=value.replace(/[^\\d]/g,\'\')" ng-class="{\'error\':_err.borrTis[$index].cellphone}" ng-focus="remFocus()" type="text" ng-blur="getPhone(key)" placeholder="请输入手机号码" ng-model="item.cellphone" class="cellphone ng-pristine ng-untouched ng-valid ng-empty">\n' +
            '\t\t\t\t\t\t</span>\n' +
            '\t\t\t\t\t<span class="pad">\n' +
            '\t\t\t\t\t\t\t<label class="sex-radio" ng-class="{\'is-checked\':item.sex == 1}">\n' +
            '\t\t\t\t\t\t\t\t<input type="radio" name="PersonMessSex_2" value="1" ng-checked="item.sex == 1" ng-model="item.sex" class="ng-pristine ng-untouched ng-valid ng-empty">男</label>\n' +
            '\t\t\t\t\t\t\t<label class="sex-radio" ng-class="{\'is-checked\':item.sex == 2}">\n' +
            '\t\t\t\t\t\t\t\t<input type="radio" name="PersonMessSex_2" value="2" ng-checked="item.sex == 2" ng-model="item.sex" class="ng-pristine ng-untouched ng-valid ng-empty">女</label>\n' +
            '\t\t\t\t\t\t</span>\n' +
            '\t\t\t\t\t<!-- ngIf: key!==0 --><span class="del ng-scope" ng-if="key!==0" ng-click="deleteBersonalName(key)">删除</span><!-- end ngIf: key!==0 -->\n' +
            '\t\t\t\t</td>\n' +
            '\t\t\t</tr>')
        $(".datepicker").datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            pickerPosition: 'bottom',
        })
        del();
        sexFun();
        addBlur();
    })

    function del() {
        $(".del").unbind().click(function () {
            $("._borrowers").eq(borrowersIndex - 1).remove();
            borrowersIndex--;
        })
    }

    function sexFun() {
        $("._borrowers td .pad .sex-radio").click(function () {
            $(this).addClass('is-checked');
            $(this).siblings().removeClass('is-checked')
            $(this).children('input').attr('checked', true)
            $(this).siblings().children('input').attr('checked', false)

        })

    }

    //身份证失去焦点触发事件
    function addBlur() {
        $('.id_card').off('blur');
        $(".id_card").on('blur', function () {
            var _this = this;
            if ($(_this).val()) {
                var m = $(_this).val()
                if (Constant.reg.isCarid.test(m)) {
                    var n = m.substring(6, 10) + "-" + m.substring(10, 12) + "-" + m.substring(12, 14);
                    $(this).parents('td').find(".birthDate").val(n).change();
                }
                var otherIdCard = $(_this).parents('tr').siblings('tr').find('.id_card');
                for (var i = 0; i < otherIdCard.length; i++) {
                    if ($(_this).val() == $(otherIdCard[i]).val()) {
                        Constant.fn.Message('I', '请勿输入相同的身份证号码')
                        return;
                    }
                }
                site.send({
                    url: url.selectInfoByCard,
                    data: {
                        idCard: $(this).val()
                    },
                    callback: function (data) {
                        data = JSON.parse(data);
                        if (data.type == 1) {
                            if(data.content){
                                Constant.fn.Message('I', '输入的身份证的号码已存在');
                                personalId = data.content.personalId;
                                $(_this).parents('td').find('.realName').val(data.content.realName);
                                $(_this).parents('td').find('.cellphone ').val(data.content.cellphone);
                                $(_this).parents('td').find('.birthDate').val(data.content.birthDate).change();
                                $(_this).parents('td').find('input[value=' + data.content.sex + ']').parent('.sex-radio').addClass('is-checked');
                            }
                            else{
                                Constant.fn.Message('T', data.msg);
                            }
                        }
                        else {
                            Constant.fn.Message('I', data.msg);
                        }
                    },
                    callError: function (err) {

                    }
                })
            }
        })
    }
    addBlur();


    //获取客户固定字段真实数据
    function getPersonalData() {

        /***********获取省市区**************/
        /*var hArea = Intelligent_association.getSearId(searData.huArea);
        var homeArea = Intelligent_association.getSearId(searData.homeArea);*/

        /*if (hArea) { */                                                 //户口所在地
        var residProvince = $("#province_list").val();
        var residCity = $("#city_list").val();
        var residArea = $("#area_list").val();
        /*}*/
        /*if (homeArea) { */                                              //居住地址
        var addrProvince = $("#rprovince_list").val();
        var addrCity = $("#rcity_list").val();
        var addrArea = $("#rarea_list").val();
        /*}*/

        /***********获取省市区**************/





        var borrowers = new Array();

        $.each($('.personMess'), function (i, e) {
            var obj = {
                id: $(e).find(".realName").attr('iid') ? $(e).find(".realName").attr('iid') : '',
                realName: $(e).find(".realName").val(),
                idCard: $(e).find(".id_card").val(),
                birthDate: $(e).find(".birth_date").val(),
                cellphone: $(e).find(".cellphone").val(),
                sex: $(e).find('.is-checked input[type="radio"]').val()
            }
            borrowers.push(obj);
        })

        //var perInfo = new Array();

        var obj = {
            payee: $("#payee").val(),
            account: $("#account").val(),
            bank: $("#bank").val(),
            residProvince: residProvince,
            residCity: residCity,
            residArea: residArea,
            residence: $('#residence').val(),
            addrProvince: addrProvince,
            addrCity: addrCity,
            addrArea: addrArea,
            address: $("#address").val(),
            house: $("#house > input[type='radio']:checked").val(),
            monthRent: $("#monthRent").val(),
            beginTime: $("#begin_time").val(),
            localTime: $("#local_time").val(),
            homephone: $("#homephone").val(),
            education: $("#education_list > option:selected").val(),
            marry: $("#marry_list > option:selected").val(),
            child: $("#child").val()
        }


        var data = {
            personalId: personalId,
            borrowers: borrowers,
            perInfo: obj
        }
        if (!getAurlparam('pid')) {
            data.product_id = productId;
        }
        return data;
    }

    //获取客户自定义表单真实数据
    function getCustomPersonData(orderProductPropertys) {

        // 拿到下半部分自定義表單
        var customForm = $('#apply-PersonMess .form_myself .component');
        $.each(customForm, function (i, e) {

            var element = $(e).find('[leipiplugins]')
            var type = element.attr('leipiplugins');

            //用来村粗content_id和value
            var content_id = '';
            var value = '';

            if (type == 'radio') {
                $.each($(e).find('[content_id]'), function (ii, ee) {
                    if ($(ee).is(':checked')) {
                        content_id = $(ee).attr('content_id');
                        value = $(ee).val();
                    }
                })
                var obj = {
                    property_id: $(e).attr('id'),
                    content_ids: content_id,
                    value: value,
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'checkbox') {
                $.each($(e).find('[content_id]'), function (ii, ee) {
                    if ($(ee).is(':checked')) {
                        content_id += $(ee).attr('content_id') + ',';
                        value += $(ee).val() + ',';
                    }
                })
                content_id = content_id.substr(0, content_id.length - 1);
                value = value.substr(0, value.length - 1);
                var obj = {
                    property_id: $(e).attr('id'),
                    content_ids: content_id,
                    value: value,
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj)
            }
            if (type == 'select') {
                $.each($(e).find('[content_id]'), function (ii, ee) {
                    if ($(ee).is(':selected')) {
                        content_id = $(ee).attr('content_id');
                        value = $(ee).val();
                    }
                })
                var obj = {
                    property_id: $(e).attr('id'),
                    content_ids: content_id,
                    value: value,
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'form_name') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('.category-title').html(),
                    type: type,
                    required: $(e).attr('require')
                };
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj)
            }
            if (type == 'text') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('input[type="text"]').val(),
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'time') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('input[type="text"]').val(),
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'textarea') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('textarea').val(),
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
        })
    }


    //保存并发起
    function saveAdd() {

        var personalData = getPersonalData();

        var orderPersonalPropertys = new Array();

        getCustomPersonData(orderPersonalPropertys);

        //personalData.orderPersonalPropertys = orderPersonalPropertys;

        //此处进行表单验证
        for (var item in personalData.borrowers) {
            //console.log('ryy:',item)
            if (!personalData.borrowers[item].realName) {
                $(".realName").eq(item).addClass('error'); //未填写标红
                Constant.fn.Message('I', '请填写借款人' + ((parseInt(item) + 1) || ''))
                return
            }
            if (!personalData.borrowers[item].idCard) {
                $(".id_card").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写身份证号码')
                return
            }

            if (!Constant.reg.isCarid.test(personalData.borrowers[item].idCard)) {
                $(".id_card").eq(item).addClass('error');
                Constant.fn.Message('I', '身份证号码格式有误！')
                return;
            }
            if (!personalData.borrowers[item].birthDate) {
                $(".birth_date").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写出生日期')
                return
            }
            if (!personalData.borrowers[item].cellphone) {
                $(".cellphone").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写手机号码')
                return
            }
            if (!Constant.reg.phone.test(personalData.borrowers[item].cellphone)) {
                $(".cellphone").eq(item).addClass('error');
                Constant.fn.Message('F', '手机号码格式有误')
                return
            }
            if (!personalData.borrowers[item].sex) {
                Constant.fn.Message('I', '请勾选性别')
                return
            }
        }

        if (!personalData.perInfo.residProvince) {
            $("#province_list").addClass('error');
            Constant.fn.Message('I', '请选择户口所在省')
            return
        }
        if (!personalData.perInfo.residCity) {
            $("#city_list").addClass('error');
            Constant.fn.Message('I', '请选择户口所在市')
            return
        }
        /*if (!personalData.perInfo.residArea) {
            $("#area_list").addClass('error');
            Constant.fn.Message('I', '请选择户口所在区')
            return
        }*/

        if (!personalData.perInfo.residence) {
            $("#residence").eq(item).addClass('error');
            Constant.fn.Message('I', '请填写户口所在地')
            return
        }

        if (!personalData.perInfo.addrProvince) {
            $("#rprovince_list").addClass('error');
            Constant.fn.Message('I', '请选择房产所在省')
            return
        }

        if (!personalData.perInfo.addrCity) {
            $("#rcity_list").addClass('error');
            Constant.fn.Message('I', '请选择房产所在市')
            return
        }
        /*if (!personalData.perInfo.addrArea) {
            $("#rarea_list").addClass('error');
            Constant.fn.Message('I', '请选择房产所在区')
            return
        }*/

        if (!personalData.perInfo.address) {
            $("#address").eq(item).addClass('error');
            Constant.fn.Message('I', '请填写房产地址')
            return
        }

        /*personalData.borrowers = JSON.stringify(personalData.borrowers);
        personalData.perInfo = JSON.stringify(personalData.perInfo);*/
        personalData.orderPersonalPropertys = orderPersonalPropertys;


        //对客户信息自定义表单进行验证


        for (var i = 0; i < orderPersonalPropertys.length; i++) {
            if (orderPersonalPropertys[i].required == 1 && !orderPersonalPropertys[i].value) {
                if (orderPersonalPropertys[i].type == 'text' || orderPersonalPropertys[i].type == 'textarea') {
                    $("[id=" + orderPersonalPropertys[i].property_id + "][leipiplugins]").addClass('error')
                }
                Constant.fn.Message('I', '请填写' + $("[id=" + orderPersonalPropertys[i].property_id + "] [leipiplugins]").attr("name"));
                return false
            }
        }

        site.send({
            type: "POST",
            url: url.addOrEdit,
            //contentType: "application/json",
            data: {
                personalInfos: JSON.stringify(personalData)
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    Constant.fn.Message('T', data.msg);
                    history.go(-1);
                    // fillFormData()
                    if (locked == 1) {
                        pjaxGo('customerManager/customerlist/customer_list.html')
                    } else if (locked == 2) {
                        pjaxGo('customerManager/customerlist/customer_blacklist.html')
                    }
                } else {
                    Constant.fn.Message('F', data.msg)
                }
            }, callError: function () {

            }
        })
        return true;
    }

    $("#selCommit").click(function () {
        saveAdd();

    })


})